package com.leo.interview;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 感觉有问题，try嵌套问题，信号量释放问题
 *      没有阻塞访问程序，一段时间尝试后就返回失败
 * @author xuexiaolei
 * @version 2017年11月03日
 */
public class FlowControl {
    private final static int MAX_COUNT = 10;
    private final Semaphore semaphore = new Semaphore(MAX_COUNT);
    private final ExecutorService exec = Executors.newCachedThreadPool();

    public void access(){
        exec.execute(new Runnable() {
            @Override public void run() {
                try {
                    if (semaphore.tryAcquire(70, TimeUnit.MILLISECONDS)){
                        try {
                            Thread.sleep(new Random().nextInt(100));
                            System.out.println("访问成功");
                        }finally {
                            semaphore.release();
                        }
                    }else {
                        System.out.println("访问失败");
                    }
                } catch (InterruptedException e) {
                    System.out.println("访问失败");
                }
            }
        });
    }

    public void shutdown(){
        exec.shutdown();
    }

    public static void main(String[] args) {
        FlowControl flowControl = new FlowControl();
        for (int i = 0; i < 30; i++) {
            flowControl.access();
        }
        flowControl.shutdown();
    }
}
